//
//  UCDownloadManager.m
//  SDK开发版本
//
//  Created by 北京国泰北斗科技有限公司 on 2016/12/30.
//  Copyright © 2016年 北京国泰北斗科技有限公司. All rights reserved.
//

#import "UCDownloadManager.h"
#import "UCDownloadArea.h"
//#import "XMNetworking.h"
#import "AeroMapServices.h"
//#import "YYCache.h"
#import "UCMapView.h"
#import "Public.h"
#import <YYCache/YYCache.h>
#import <XMNetworking/XMNetworking.h>

typedef void(^GetXYZBlcok)(int x,int y,int z);

NSString * const kDownloadClass = @"downloadClass";


@interface UCDownloadManager()

@property(nonatomic,strong,readwrite)UCDownloadArea *download;
@property(nonatomic,strong)NSString *batchrequest;
@property(nonatomic,strong)YYCache *downloadCache;
@property(nonatomic,strong)YYCache *cache;
@property(nonatomic)dispatch_queue_t queue;
@property(nonatomic)dispatch_semaphore_t semaphore;
@property(nonatomic)dispatch_semaphore_t countLock;
@property(nonatomic,assign)BOOL completion;

@end

@implementation UCDownloadManager

+ (instancetype)defaultManager{
    static dispatch_once_t onceToken;
    static UCDownloadManager *_manager;
    dispatch_once(&onceToken, ^{
        _manager = [UCDownloadManager new];
    });
    return _manager;
}

- (instancetype)init
{
    self = [super init];
    if (self) {
        self.cache = [YYCache cacheWithName:AreoMapCache];
        self.semaphore = dispatch_semaphore_create(1);
        self.countLock = dispatch_semaphore_create(1);
        self.queue = dispatch_queue_create("com.downloadQueue.com", DISPATCH_QUEUE_CONCURRENT);
    }
    return self;
}

- (void)getdownURLS:(GetXYZBlcok)blcok {
    //z  x  y
    int a = 0,b = -1,c = -1;
    UCDownloadArea *down = self.download;
    if (down) {
        for (int k = 0; k < down.levelArray.count; k++) {
            NSDictionary *dic = self.download.levelArray[k];
            int z = [dic.allKeys.lastObject intValue];
            if (z == down.z) {
                a = k;
            }
        }
        b = (int)down.x;
        c = (int)down.y;
    }
    int count = (int)self.download.levelArray.count;
    for (int k = a; k < count; k++) {
        NSDictionary *dic = self.download.levelArray[k];
        int z = [dic.allKeys.lastObject intValue];
        int startX = [[dic.allValues.lastObject objectForKey:kStartX] intValue];
        int startY = [[dic.allValues.lastObject objectForKey:kStartY] intValue];
        int endX   = [[dic.allValues.lastObject objectForKey:kEndX] intValue];
        int endY   = [[dic.allValues.lastObject objectForKey:kEndY] intValue];
        if (b > 0) {
            startX = b;
            b = -1;
        }
        if (c > 0) {
            startY = c+1;
            c = -1;
        }
        for (int i = startX; i <= endX; i++) {
            for (int j = startY; j <= endY; j++) {
                blcok(i,j,z);
            }
            startY = [[dic.allValues.lastObject objectForKey:kStartY] intValue];
        }
    }
}

///开始下载
- (void)beginDownloadWith:(UCDownloadArea *)download
                WithBlcok:(DownloadBlock)block
           withCompletion:(CompletionBlock)completionBlock{
    
    __weak typeof(self) weekSelf = self;
    dispatch_async(_queue, ^{
        __strong typeof(self) strongSelf = weekSelf;
        dispatch_semaphore_wait(_semaphore, DISPATCH_TIME_FOREVER);
        strongSelf.downloadCache = [YYCache cacheWithName:download.cacheName];
        strongSelf.download = download;
        AeroMapServices *service = [AeroMapServices shareServices];
        
        strongSelf.batchrequest = [XMCenter sendBatchRequest:^(XMBatchRequest * _Nonnull batchRequest) {
            [batchRequest.requestArray removeAllObjects];
            [weekSelf getdownURLS:^(int x, int y, int z) {
                XMRequest *request = [XMRequest request];
                NSString *identifier = [NSString stringWithFormat:@"%d%d%d",x,y,z];
                [request setValue:identifier forKey:@"identifier"];
                request.requestType = kXMRequestDownload;
                request.httpMethod = kXMHTTPMethodGET;
                request.responseSerializerType = kXMResponseSerializerRAW;
                request.downloadSavePath = [NSHomeDirectory() stringByAppendingString:@"/Documents/"];
                //                request.headers = @{@"Authorization":value};
                request.url = [NSString stringWithFormat:@"%@/%@/%d/%d/%d?%@%@",UCMAPTITLEURL,self.download.mapType,z,y,x,UCMAPKEY,[service valueForKey:@"AeroMapAK"]];
                
                //每一个成功的回调
                XMSuccessBlock successBlock = ^(id responseObject){
                    if (strongSelf.download.downloadCount < strongSelf.download.sumCount) {
                        dispatch_semaphore_wait(_countLock, DISPATCH_TIME_FOREVER);
                        strongSelf.download.downloadCount += 1;//已经下载的数量
                        strongSelf.download.progress = strongSelf.download.downloadCount*1.0f/strongSelf.download.sumCount*1.0f;//下载进度
                        [strongSelf.download getDownloadProgressWith:strongSelf.download.downloadCount*50.0/1024.0];
                        strongSelf.download.progressState = UCDownloading;
                        if (z > strongSelf.download.z) {
                            [strongSelf.download setValue:@(z) forKey:@"z"];
                            [strongSelf.download setValue:@(x) forKey:@"x"];
                            [strongSelf.download setValue:@(y) forKey:@"y"];
                        }else if (z == strongSelf.download.z){
                            if (x > strongSelf.download.x) {
                                [strongSelf.download setValue:@(x) forKey:@"x"];
                                [strongSelf.download setValue:@(y) forKey:@"y"];
                            }else if (x == self.download.x && y > self.download.y){
                                [strongSelf.download setValue:@(y) forKey:@"y"];
                            }
                        }
                        [strongSelf.downloadCache setObject:self.download forKey:kDownloadClass];//保存下载的对象
                        block ? block(strongSelf.download.progress) : nil;
                        dispatch_semaphore_signal(_countLock);
                    }
                };
                [request setValue:successBlock forKey:@"_successBlock"];
                
                XMFailureBlock failureBlock = ^(NSError * _Nullable error){
#ifdef DEBUG
                    NSLog(@"AeroMapDownloadError:%@",error);
#endif
                };
                [request setValue:failureBlock forKey:@"_failureBlock"];
                
                [batchRequest.requestArray addObject:request];
            }];
        } onSuccess:^(NSArray<id> * _Nonnull responseObjects) {
#ifdef DEBUG
            NSLog(@"AeroMapDownloadSuccess:下载成功的数量:%lu",(unsigned long)responseObjects.count);
#endif
        } onFailure:^(NSArray<id> * _Nonnull errors) {
#ifdef DEBUG
            NSLog(@"AeroMapDownloadError:download error count = %lu",(unsigned long)errors.count);
#endif
        } onFinished:^(NSArray<id> * _Nullable responseObjects, NSArray<id> * _Nullable errors) {
            
            strongSelf.download.progressState = UCDownloadCompletion;
            [strongSelf.downloadCache setObject:strongSelf.download forKey:kDownloadClass];
            for (int i = 0; i < responseObjects.count; i++) {
                if ([responseObjects[i] isKindOfClass:[NSDictionary class]]) {
                    NSDictionary *dic = responseObjects[i];
                    NSData *data = [[NSFileManager defaultManager] contentsAtPath:dic.allValues.lastObject];
                    UIImage *image = [UIImage imageWithData:data];
                    [strongSelf.cache setObject:image forKey:dic.allKeys.lastObject];
                    [[NSFileManager defaultManager] removeItemAtPath:dic.allValues.lastObject error:nil];
                }
            }
            completionBlock();
            dispatch_semaphore_signal(_semaphore);
        }];
    });
}

- (void)pauseDownload{
    
    __weak typeof(self) weekSelf = self;
    dispatch_async(_queue, ^{
        [XMCenter cancelRequest:self.batchrequest onCancel:^(id  _Nullable request) {
            dispatch_semaphore_signal(weekSelf.semaphore);
            self.download.progressState = UCDownloadPause;
            [self.downloadCache setObject:weekSelf.download forKey:kDownloadClass withBlock:^{
            }];
        }];
    });
}

- (void)recoverDownloadWithName:(NSString *)name
                      withBlcok:(DownloadBlock)block
                 withCompletion:(CompletionBlock)completionBlock{
    
    self.downloadCache = [YYCache cacheWithName:name];
    UCDownloadArea *download = (UCDownloadArea *)[self.downloadCache objectForKey:kDownloadClass];
    if (download.progressState == UCDownloadCompletion) {
        //        NSLog(@"已经下载完毕");
        completionBlock();
        return ;
    }
    [self beginDownloadWith:download WithBlcok:block withCompletion:completionBlock];
}

- (void)removeCache:(NSString *)cacheName{
    YYCache *cache = [YYCache cacheWithName:cacheName];
    [cache removeAllObjectsWithBlock:^{
        
    }];
}
@end
